﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Achievement.Web.Common;
using Achievement.DataModels;
using Achievement.BLL.Provider;
using Achievement.Common;
using Ebooom.Leads.Business.AuthorRole;
using System.Dynamic;

namespace Achievement.Web.Controllers
{
    [Authorize]
    public class UsersController : Controller
    {
        //
        // GET: /Users/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult EditPwd()
        {
            return View();
        }

        [HttpPost]
        public ActionResult EditPwd(string txtOP,string txtNP)
        {
            txtOP = ATools.MD5Encrypt(txtOP);
            txtNP = ATools.MD5Encrypt(txtNP);
            if (UserInfo.CurrentUser.PassWord == txtOP)
            {
                Users user = UsersProvider.Instance.GetUserById(UserInfo.CurrentUser.ID);
                user.PassWord = txtNP;
                UsersProvider.Instance.SaveUser(user);
            }
            else 
            {
                return Content(ATools.OperateAlter("原密码错误！", "/Users"));
            }
            return Redirect("/Users");
        }

        [HttpPost]
        public ActionResult list(string where, int page, int rows, string sord, string sidx)
        {
            int totalRecords = 0;
            var userList = UsersProvider.Instance.GetUserList(where, page, rows, sord, sidx, out totalRecords);
            var json = new
            {
                total = (int)Math.Ceiling((double)totalRecords / rows),
                page = page,
                records = totalRecords,
                rows = from c in userList
                       select new
                       {
                           id = c.ID,
                           cell = new[] { c.ID.ToString(), c.Name, c.LoginName, c.WorkNumber, c.WorkDate.ToString(), c.Position, c.Department,c.IsActive.ToString(), 
                               (UserInfo.ValidataRole(1)?"<a href=\"javascript:void(0)\" onclick=\"$.facebox({ ajax: '/users/getAuthority?id=" + c.ID + "'})\">权限</a>" + 
                                "&nbsp;&nbsp;<a href=\"/users/edituser?id=" + c.ID + "\">编辑</a>" + 
                                "&nbsp;&nbsp;<a href=\"javascript:void(0)\" onclick=\"return deleteuser(" + c.ID + ")\">删除</a>" + 
                                (!c.IsActive?"&nbsp;&nbsp;<a href=\"javascript:UserAuditing(" + c.ID + ")\">审核通过</a>":""):"")
                                }
                       }
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }


        public ActionResult EditInfo()
        {
            Users u = UsersProvider.Instance.GetUserById(UserInfo.CurrentUser.ID);
            return View(u);
        }

        [AuthorizeFilter(ValidataRole = 1)]
        public ActionResult EditUser(long? id)
        {
            long uid = id.SecureToLong();
            Users u = new Users();
            if (uid > 0)
            {
                u = UsersProvider.Instance.GetUserById(uid);
            }
            return View("EditInfo", u);
        }

        [HttpPost]
        public ActionResult SaveInfo(Users u)
        {
            string fileName = string.Empty;
            if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
            {
                HttpPostedFileBase file = Request.Files[0];
                string fileExtension = string.Empty;
                fileName = CommonTools.UploadFile(file, out fileExtension);
            }
            if (u.ID > 0)
            {
                Users ou = UsersProvider.Instance.GetUserById(u.ID);
                ou.Name = u.Name;
                ou.Position = u.Position;
                ou.Resume = u.Resume;
                ou.WorkDate = u.WorkDate;
                ou.WorkNumber = u.WorkNumber;
                ou.PassWord = ATools.MD5Encrypt(u.PassWord);
                if (!string.IsNullOrEmpty(fileName))
                {
                    ou.Image = fileName;
                }
                UsersProvider.Instance.SaveUser(ou);
            }
            else
            {
                u.IsActive = true;
                u.CreateTime = DateTime.Now;
                u.UploadSize = 80;
                u.Display = true;
                if (!string.IsNullOrEmpty(fileName))
                {
                    u.Image = fileName;
                }
                UsersProvider.Instance.AddUser(u);
            }
            
            return Redirect("/Users");
        }

        public ActionResult GetAuthority(long id)
        {
            Users u = UsersProvider.Instance.GetUserById(id);
            List<Authority> aty = AuthorityProvider.Instance.GetAuthorityList();
            dynamic v = new ExpandoObject();
            v.List = new List<ExpandoObject>();
            v.UploadSize = u.UploadSize;
            v.UID = id;
            foreach (var item in aty)
            {
                dynamic i = new ExpandoObject();
                i.Name = item.Name;
                i.AID = item.AID;
                i.Role = AuthorRoleUtils.IsHasRight(u.Roles.SecureToLong(), item.AID);
                v.List.Add(i);
            }
            return View(v);
        }

        [HttpPost]
        public ActionResult SaveRoles(string[] ckbRoles,string txtUploadLimit, long uid)
        {
            long role = 0;
            foreach (var item in ckbRoles)
            {
                role = AuthorRoleUtils.SetRoleForUser(role, item.SecureToLong());
            }
            AuthorityProvider.Instance.CovertRole(uid, role, txtUploadLimit);
            return Redirect("/users");
        }

        public ActionResult UserAuditing(long id)
        {
            UsersProvider.Instance.UserAuditing(id,true);
            return Redirect("/users");
        }

        public ActionResult Delete(long id)
        {
            UsersProvider.Instance.DeleteUser(id);
            return Redirect("/users");
        }
    }
}
